package it.softphone.cmc.server.rest;

import it.softphone.cmc.server.rest.scriptlet.CMCAbstractScriptletExecutionManager;
import it.softphone.cmc.server.service.ScriptletManagerService;
import it.softphone.cmc.server.service.exception.CMCException;
import it.softphone.commons.spring.ApplicationConfig;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/exec")
public class CMCScriptletExcecutionManager extends CMCAbstractScriptletExecutionManager  {

	protected ScriptletManagerService script() {

		ScriptletManagerService service = ApplicationConfig.getBean(ScriptletManagerService.class);
		
		return service;
		
	}

    @Context UriInfo ui;
    @Context HttpHeaders hh;
	
    /**
     * use post version
     * 
     * @param key
     * @return
     */
    
	@GET 
    @Produces( {MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON } )
    @Path("{mode: (async:)?}{Key}")
    public Response execScriptlet(	@PathParam("mode") String mode, 
    								@PathParam("Key") final String key ) throws CMCRestException {

		//checkPermission( Permissions.Script.EXEC ) ;

		logger.debug( String.format("execScriptlet GET\n\tmode=[%s]\n\tkey=[%s]", mode, key));
		
		final MultivaluedMap<String,String> params = ui.getQueryParameters();
		
		final String callback = params.getFirst("callback");
		
		String entityResult = null;
		
		if("async:".equals(mode)) {

			execScriptletAsync( key, hh,  ui, params, HttpMethod.GET );
			entityResult = "{status:'OK', msg:'task scheduled'}";
			
		}
		else {
			entityResult = execScriptletSync( key , hh, ui, params, HttpMethod.GET );
		}
			
		if( callback!=null ) { // JSONP AWARE
			return Response.ok( new StringBuilder()
							.append( callback )
							.append('(')
							.append(entityResult)
							.append(");")
							.toString() ).type(MediaType.APPLICATION_JSON).build();								
		}
		else {

			return Response.ok(entityResult).type(MediaType.TEXT_PLAIN).build();
		}
		
    }
	
	
	/**
	 * 
	 * @param mode
	 * @param key
	 * @param inFormParams
	 * @return
	 * @throws CMCException
	 */
	@POST 
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON})
    @Path("{mode: (async:)?}{Key}")
    public Response execScriptlet( 
    		@PathParam("mode") String mode, 
    		@PathParam("key") final String key,
    		MultivaluedMap<String,String> inFormParams
    		  ) throws CMCRestException
	{

		
		//checkPermission( Permissions.Script.EXEC ) ;
		
		
		logger.debug( String.format("execScriptlet POST\n\tmode=[%s]\n\tkey=[%s]", mode, key));
		
		if( logger.isTraceEnabled() ) {

			logger.trace("Parameters");
			
			for( String k : inFormParams.keySet()) {

				logger.trace( String.format("\t[%s]=[%s]", k, inFormParams.getFirst(k)));
				
			}
		}
		
		if(  "async:".equals(mode)) {
			
			execScriptletAsync( key, hh,  ui, inFormParams, HttpMethod.POST );
			return Response.ok("{status:'OK', msg:'task scheduled'}").type(MediaType.TEXT_PLAIN).build();

		}
		else {
			
			String entityResult =  execScriptletSync( key , hh, ui, inFormParams, HttpMethod.POST );
			return Response.ok(entityResult).type(MediaType.TEXT_PLAIN).build();

		}
    }
	

}
